package com.study.web.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.study.web.datasource.DatabaseContextHolder;

/**
 * 系统功能：动态数据源 AOP实现<br>
 * ResponseTimeAop.java
 * 
 * @author yaojinshan
 * @since 2018年6月14日上午10:10:56
 */
@Aspect
@Order(-1)
@Component
public class DataSourceAop {

	static Logger logger = LoggerFactory.getLogger(DataSourceAop.class);
	private static String dataSource_master = "masterdataSource";
	private static String dataSource_slave = "slavedataSource";
	
	@Pointcut("execution(* com.study.web.action..*.*(..))")
	//action包及子包的所有切入点
	public void dataSourceAopExpression() {

	}
	@Pointcut("execution(* com.study.web.action.RequestPageController.*(..))")
	//请求是页面请求切入点
	public void dataSourceAopExpression1() {
		
	}
	@Before("dataSourceAopExpression() and !dataSourceAopExpression1()") // 该标签声明次方法是一个前置通知：在目标方法开始之前执行
	//同时满足两个切入点 '!'代表取反
	public void beforMethod(JoinPoint joinPoint) {
		String exeName = joinPoint.getSignature().getName();// 当前执行方法的名称
		if (exeName.startsWith("query") || exeName.startsWith("get")) {
			DatabaseContextHolder.setCustomerType(dataSource_master);
		} else {
			DatabaseContextHolder.setCustomerType(dataSource_master);
		}
	}

	@After("dataSourceAopExpression()")
	public void afterMethod(JoinPoint joinPoint) {
	}

	@AfterReturning(value = "dataSourceAopExpression()", returning = "result")
	public void afterReturnMethod(JoinPoint joinPoint, Object result) {
	}

	@AfterThrowing(value = "dataSourceAopExpression()", throwing = "ex")
	public void afterThrowingMethod(JoinPoint joinPoint, Exception ex) {
	}

	@Around(value = "dataSourceAopExpression()")
	public Object aroundMethod(ProceedingJoinPoint pjp) throws Throwable {
		Object result = pjp.proceed();
		return result;
	}
}
